package com.syqc.videos.videomanager

import android.app.Activity
import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.Window
import com.shuyu.gsyvideoplayer.GSYVideoBaseManager
import com.shuyu.gsyvideoplayer.model.VideoOptionModel
import com.shuyu.gsyvideoplayer.player.IPlayerManager
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.utils.CommonUtil
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import com.syqc.monitor.R
import tv.danmaku.ijk.media.player.IjkMediaPlayer

/**
 * 多个播放的管理器
 * Created by guoshuyu on 2018/1/31.
 */
class PlayerManager : GSYVideoBaseManager() {
    init {
        init()
        initVideoOptions()
        isNeedMute = true
    }

    override fun getPlayManager(): IPlayerManager {
        return IjkPlayerManager()
    }

    /**
     * 暂停播放
     */
    fun onPause(key: String) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoPause()
        }
    }

    /**
     * 恢复播放
     */
    fun onResume(key: String) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoResume()
        }
    }

    /**
     * 设置是否需要静音
     *
     * @param key
     * @param isNeedMute
     */
    fun setNeedMute(key: String, isNeedMute: Boolean) {
        sMap.forEach { (t, u) ->
            if (t == key) {
                u.isNeedMute = isNeedMute
                u.voiceListener?.onMuteChange(isNeedMute)
            } else {
                u.isNeedMute = true
                u.voiceListener?.onMuteChange(true)
            }

        }
    }

    fun setPassChoose(key: String, isChoose: Boolean) {
        sMap.forEach { (t, u) ->
            u.voiceListener?.onPassChange(if (t == key) isChoose else false)
        }
    }

    private var voiceListener: IPlayerListener? = null
    fun setVoiceListener(listener: IPlayerListener) {
        this.voiceListener = listener
    }

    /**
     * 恢复暂停状态
     *
     * @param seek 是否产生seek动作,直播设置为false
     */
    fun onResume(key: String, seek: Boolean) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoResume(seek)
        }
    }

    companion object {
        val SMALL_ID = R.id.custom_small_id
        val FULLSCREEN_ID = R.id.custom_full_id
        private val sMap: MutableMap<String, PlayerManager> = HashMap()

        /**
         * 退出全屏，主要用于返回键
         *
         * @return 返回是否全屏
         */
        fun backFromWindowFull(context: Context?, key: String): Boolean {
            var backFrom = false
            val vp = CommonUtil.scanForActivity(context)
                .findViewById<View>(Window.ID_ANDROID_CONTENT) as ViewGroup
            val oldF = vp.findViewById<View>(FULLSCREEN_ID)
            if (oldF != null) {
                backFrom = true
                CommonUtil.hideNavKey(context)
                if (getCustomManager(key).lastListener() != null) {
                    getCustomManager(key).lastListener().onBackFullscreen()
                }
            }
            return backFrom
        }

        /**
         * 页面销毁了记得调用是否所有的video
         */
        fun releaseAllVideos(key: String) {
            if (getCustomManager(key).listener() != null) {
                getCustomManager(key).listener().onCompletion()
            }
            getCustomManager(key).releaseMediaPlayer()
        }

        /**
         * 单例管理器
         */
        @Synchronized
        fun instance(): Map<String, PlayerManager> {
            return sMap
        }

//        fun allNeedMute() {
//            sMap.forEach { t, u ->
//                u.isNeedMute = true
//                u.voiceListener?.onMuteChange(true)
//            }
//        }

        /**
         * 单例管理器
         */
        @Synchronized
        fun getCustomManager(key: String): PlayerManager {
            check(!TextUtils.isEmpty(key)) { "key not be empty" }
            var customManager = sMap[key]
            if (customManager == null) {
                customManager = PlayerManager()
                sMap[key] = customManager
            }
            return customManager
        }


        fun onPauseAll() {
            if (sMap.isNotEmpty()) {
                for ((key, value) in sMap) {
                    value.onPause(key)
                }
            }
        }

        fun onResumeAll() {
            if (sMap.isNotEmpty()) {
                for ((key, value) in sMap) {
                    value.onResume(key)
                }
            }
        }

        /**
         * 恢复暂停状态
         *
         * @param seek 是否产生seek动作
         */
        fun onResumeAll(seek: Boolean) {
            if (sMap.isNotEmpty()) {
                for ((key, value) in sMap) {
                    value.onResume(key, seek)
                }
            }
        }

        fun clearAllVideo() {
            if (sMap.isNotEmpty()) {
                for ((key) in sMap) {
                    releaseAllVideos(key)
                }
            }
            sMap.clear()
        }

        fun clearAllNorAudio(audioKey: String) {
            if (sMap.isNotEmpty()) {
                val list = sMap.filter { it.key != audioKey }
                for ((key,value ) in list) {
                    value.releaseMediaPlayer()
                    releaseAllVideos(key)
                    sMap.remove(key)
                }
            }
        }

        fun removeManager(key: String?) {
            sMap.remove(key)
        }

        /**
         * 当前是否全屏状态
         *
         * @return 当前是否全屏状态， true代表是。
         */
        fun isFullState(activity: Activity?): Boolean {
            val vp = CommonUtil.scanForActivity(activity)
                .findViewById<View>(Window.ID_ANDROID_CONTENT) as ViewGroup
            val full = vp.findViewById<View>(FULLSCREEN_ID)
            var gsyVideoPlayer: GSYVideoPlayer? = null
            if (full != null) {
                gsyVideoPlayer = full as GSYVideoPlayer
            }
            return gsyVideoPlayer != null
        }
    }


    private fun initVideoOptions() {
        val list: MutableList<VideoOptionModel> = ArrayList()
//        //开启硬解码
//        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1))
//        //开启软解码
//        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "videotoolbox", 0))
        //过小会延迟
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 3096))
        //无限读
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", 1))
        //分析码流时长
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100))
        //  自动开始播放已准备好的
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0))
        //默认值48
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 48))
        //不设置会加长延迟
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240))
        // 清空DNS,有时因为在APP里面要播放多种类型的视频(如:MP4,直播,直播平台保存的视频,和其它http视频), 有时会造成因为DNS的问题而报10000问题的
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_clear", 1))
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1))
        //最大缓存数
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", 0))
        //默认最小帧数2
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", 2))
        //丢帧,太卡可以尝试丢帧
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 5))
        //关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0))
        setOptionModelList(list)
    }


}

interface IPlayerListener {
    fun onMuteChange(isNeedMute: Boolean)
    fun onPassChange(isChoose: Boolean)
}